package com.yangye.picommon.utils;

import com.yangye.picommon.model.TreeNode;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangye
 * @date 2019/8/6
 */
public class TreeUtil {

	public static <E extends TreeNode<E>> List<E> parseTree(List<E> list) {
		// 获取顶层元素集合
		List<E> pList = list.stream().
				filter(v -> v.getParentId() == 0L).collect(Collectors.toList());

		// 获取子元素集合
		for (TreeNode node : pList) {
			recursiveTree(node, list);
		}
		return pList;
	}

	private static <E extends TreeNode<E>> void recursiveTree(TreeNode pNode, List<E> list) {
		for (E node : list) {
			if (node.getParentId() == pNode.getId()) {
				pNode.getChildren().add(node);
				recursiveTree(node, list);
			}
		}
	}
}
